<!-- 数据导入弹框组件 -->
<template>
    <el-dialog v-model="dialogVisible" @close="cancleUpload" title="导入数据" width="30%">
        <slot name="slotsSelect"></slot>
        <div class="downloadModel">
            下载导入模板<span @click="importTemplate">{{ downloadFileName }}</span>
        </div>
        <!-- 选择单位 -->
        <div v-if="showSelect" class="mb10">
            <el-form ref="queryRef1" label-position="right" :model="params" label-width="120px" :rules="rules">
                <el-form-item label="省：" prop="province">
                    <el-select v-model="params.province" placeholder="请选择省" clearable disabled>
                        <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="市：" prop="city">
                    <el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable>
                        <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="县：" prop="county">
                    <el-select v-model="params.county" placeholder="请选择县" clearable>
                        <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <el-upload ref="uploadRef" v-model:file-list.sync="fileList" :action="uploadFileUrl"
            :data="{ ...params, type: props.types }" :before-upload="beforeUpload" :before-remove="beforeRemove"
            :on-success="uploadSuccess" :on-error="uploadError" :headers="headers" :multiple="false" :limit="1"
            :auto-upload="false">
            <el-button type="primary" class="icon-Angle-upload">选择本地文件</el-button>
        </el-upload>
        <template #footer>
            <span class="dialog-footer">
                <el-button size="default" @click="cancleUpload">取 消</el-button>
                <el-button size="default" type="primary" @click="submitUpload">确定上传？</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
// 引入store
import useUserStore from '@/store/modules/user';
// 获取token
import { getToken } from "@/utils/auth";
import { computed, watch } from "vue";
import { getProvince, getChildArea } from "@/api/system/division";
// 获取当前实例
const { proxy } = getCurrentInstance();
// 上传成功回调
const emit = defineEmits(['update:modelValue', 'importSuccess']);
// 接口根路径
const baseURL = import.meta.env.VITE_APP_BASE_API;
// 设置token
const headers = ref({ token: "token " + getToken() });
// 获取pinia
const userStore = useUserStore();
// 接收父组件传参
const props = defineProps({
    // 显示弹框
    modelValue: {
        type: Boolean,
        required: false,
        default: () => false,
    },
    // 下载模板名称
    downloadFileName: {
        type: String,
        required: false,
        default: () => '',
    },
    // 上传接口
    uploadUrl: {
        type: String,
        required: false,
        default: () => '',
    },
    // 是否显示下拉选择
    isShow: {
        type: Boolean,
        required: false,
        default: false,
    },
    // 业务类型
    types: {
        String,
        required: false,
        default: () => '',
    },
    provinceData: {
        type: Array,
        required: false,
        default: () => [],
    },
    cityData: {
        type: Array,
        required: false,
        default: () => [],
    },
});
let rules = ref({
    province: [{ required: true, message: '请选择', trigger: 'change' }],
    city: [{ required: true, message: '请选择', trigger: 'change' }],
    county: [{ required: true, message: '请选择', trigger: 'change' }],
})

// 显示下拉框
const showSelect = computed(
    () => props.isShow
);
// 选择区域
let params = ref({
    province: userStore.provinceId,
    city: '',
    county: '',
});

// 模板下载
function importTemplate() {
    proxy.download("/base/product/downloadExcel", {
        fileName: props.downloadFileName
    }, props.downloadFileName);
};

// 文件上传对象
const uploadRef = ref();
// 显示弹框
const dialogVisible = ref(props.modelValue);
// 关闭上传弹框
const cancleUpload = () => {
    dialogVisible.value = false;
    emit('update:modelValue', false);
}
// 提交上传
const submitUpload = (res) => {
    // 如果显示选择单位，则必填
    if (props.isShow) {
        proxy.$refs["queryRef1"].validate(valid => {
            if (!valid) {
                return false;
            }else{
                uploadRef.value.submit();
            }
        });
    }else{
        uploadRef.value.submit();
    }
}

//文件上传
const uploadFileUrl = ref(baseURL + props.uploadUrl); //上传地址
const fileList = ref([]); //上传文件列表
// 删除附件前回调
const beforeRemove = () => {
    fileList.value = [];
};
// 上传前回调
const beforeUpload = (file) => {
    const fileSize = file.size / 1024 / 1024;
    if (fileSize > 200) {
        $message.error('文件大小不能超过200M!');
        return false;
    }
    const fileReg = /.xls|.xlsx/;
    if (!fileReg.test(file.name)) {
        $message.error('请选择.xls .xlsx格式文件');
        return false;
    }
    // 导入等待提示动画
    proxy.$modal.loading('数据导入中,请耐心等待！');
    return true;
};
// 上传成功回调
const uploadSuccess = (response, uploadFile, uploadFiles) => {
    // 关闭提示动画
    proxy.$modal.closeLoading();
    if (response.code === 200) {
        dialogVisible.value = false;
        emit('update:modelValue', false);
        // 调用父组件方法
        emit("importSuccess", response, uploadFile, uploadFiles);
    } else {
        proxy.$modal.msgError(response.message || "导入失败，请检查表头是否改动");
    }
}
// 上传失败回调
const uploadError = (err, uploadFile, uploadFiles) => {
    // 关闭提示动画
    proxy.$modal.closeLoading();
    proxy.$modal.msgError(err.message || "导入失败，请检查表头是否改动");
}


// 行政区划
const provinceData = computed(() => {
    return props.provinceData;
}); //省
const cityData = computed(() => {
    return props.cityData;
}); //市

let areaData = ref([]); //区、县

// 选择城市
function chooseCity(value) {
    params.value.city = value;
    params.value.county = null;
    areaData.value = [];
    getChildArea(value).then((response) => {
        areaData.value = response.data;
    });
}
// 选择区县
function chooseCounty(value) {
    console.log('1111');
    console.log(value);
    //   params.value.county = value;
}
</script>

<style lang="scss">
.downloadModel {
    font-size: 16px;
    line-height: 60px;

    span {
        color: #107ce5;
        cursor: pointer;
    }
}
</style>